package com.example.source.debezium;

import java.util.Map;


public class SQLUtils {

    public static String genSqlInsert(Map<String, Object> dataMap,String tableName) {
        if(dataMap.size()==0) {
            return null;
        }

        //生成INSERT INTO table(field1,field2) 部分
        StringBuffer sbField = new StringBuffer();
        //生成VALUES('value1','value2') 部分
        StringBuffer sbValue = new StringBuffer();

        sbField.append("INSERT INTO " + tableName.toLowerCase() + "(");

        for(Map.Entry<String, Object> entry : dataMap.entrySet()){
            String mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            if(mapValue instanceof String){
                sbValue.append("'" + mapValue + "',");
            }else{
                sbValue.append(mapValue + ",");
            }

            sbField.append("`" + mapKey + "`,");
        }

        String sbFieldStr = sbField.toString();
        String sbValueStr = sbValue.toString();
        if(sbFieldStr.endsWith(",")){
            sbFieldStr = sbFieldStr.substring(0,sbFieldStr.length()-1);
        }

        if(sbValueStr.endsWith(",")){
            sbValueStr = sbValueStr.substring(0,sbValueStr.length()-1);
        }

        return sbFieldStr + ") VALUES(" + sbValueStr + ")";
    }

    public static String genSqlDelete(Map<String, Object> dataMap,String tableName) {
        if(dataMap.size()==0) {
            return null;
        }

        //生成DELETE FROM xxx where  部分
        StringBuffer sbField = new StringBuffer();
        //生成id = zhangsan and sex = 1
        StringBuffer sbValue = new StringBuffer();

        sbField.append("DELETE FROM " + tableName.toLowerCase() + " where ");

        for(Map.Entry<String, Object> entry : dataMap.entrySet()){
            String mapKey = entry.getKey();
            Object mapValue = entry.getValue();
            if(mapValue instanceof String){
                sbValue.append("and "+mapKey+"='" + mapValue + "' ");
            }else{
                sbValue.append("and "+mapKey+"=" + mapValue + " ");
            }
        }

        String sbFieldStr = sbField.toString();
        String sbValueStr = sbValue.toString();

        if(sbValueStr.startsWith("and")){
            sbValueStr = sbValueStr.substring(3);
        }

        if(sbValueStr.endsWith(",")){
            sbValueStr = sbValueStr.substring(0,sbValueStr.length()-1);
        }

        return sbFieldStr + sbValueStr ;
    }

}